/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RRHH_controlador;

import CONTABILIDAD_MODELO.CON_FECHA_CIERRE;
import CONTABILIDAD_MODELO.CON_RECURRENTES_MENSUALES;
import Conexion.Conexion;
import RRHH_Modelo.RHH_PAGO_SUBSIDIOS;
import RRHH_Modelo.RHH_PERSONA;
import RRHH_Modelo.RHH_SUBSIDIOS;
import RRHH_Modelo.RHH_USUARIO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author equipo_4
 */
@WebServlet(name = "RRHH_SUBSIDIOS_CONTROLLER", urlPatterns = {"/RRHH_SUBSIDIOS_CONTROLLER"})
public class RRHH_SUBSIDIOS_CONTROLLER extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RRHH_SUBSIDIOS_CONTROLLER</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RRHH_SUBSIDIOS_CONTROLLER at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            RHH_USUARIO usuario = ((RHH_USUARIO)request.getSession().getAttribute("usr"));                     
            Conexion con = new Conexion(usuario.getUSUARIO(), usuario.getPASSWORD());
            String evento =request.getParameter("evento");
                String html="";
            switch(evento)
            {
                case "insertar":
                    html=insertar(request,con);
                    break;
                case "cuotas":
                    html=cuotas(request,con);
                    break;
                case "crear3":
                    html=crear3(request,con);
                    break;
                case "pagar":
                    html=pagar(request,con);
                    break;
                case "eliminar":
                    html=eliminar(request,con);
                    break;
                case "anular":
                    html=anular(request,con);
                    break;
                case "inicio":
                    html=inicio(request,con);
                    break;
            }
            
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            response.getWriter().write(html);
            con.Close();
        } catch (ParseException ex) {
            response.sendRedirect("index.jsp");
            Logger.getLogger(RRHH_SUBSIDIOS_CONTROLLER.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(RRHH_SUBSIDIOS_CONTROLLER.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String insertar(HttpServletRequest request, Conexion con) throws ParseException, SQLException {
        String html="";
        String usuario = request.getParameter("usuario");
        String natalidad = request.getParameter("natalidad");
        String bebefic = request.getParameter("bebefic");
        String date = request.getParameter("date");
        
        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
        RHH_SUBSIDIOS sub = new RHH_SUBSIDIOS(0, Integer.parseInt(usuario), Integer.parseInt(natalidad), bebefic, formato.parse(date));
        sub.setCon(con);
        int idsub=sub.Insertar();
        RHH_USUARIO us = new RHH_USUARIO(con).BuscarXid(Integer.parseInt(usuario));
        RHH_PERSONA per = new RHH_PERSONA(con).BuscarxID(us.getID_PERSONA());
        
        html+="<tr><td>"+per.getCI()+"</td><td>"+per.getPRIMER_NOMBRE()+"</td><td>"+per.getPRIMER_APELLIDO()+"</td><td>"+bebefic+"</td><td><a href='#' onclick='cuotas("+idsub+");'>Asignar plan de pago</a></td>";

        if(Integer.parseInt(natalidad)==0)
            html+="<td>PRE-NATAL</td>";
        if(Integer.parseInt(natalidad)==1)
            html+="<td>NATALIDAD</td>";
        if(Integer.parseInt(natalidad)==2)
            html+="<td>POST-NATAL</td>";
        
        html+="<td>"+date+"</td></tr>";
        return html;
    }

    private String cuotas(HttpServletRequest request, Conexion con) throws SQLException {
        String html="";
        int idsub = Integer.parseInt(request.getParameter("idsub"));
        List<RHH_PAGO_SUBSIDIOS> pagos = new RHH_PAGO_SUBSIDIOS(con).TodosxSubsidio(idsub);
        
        CON_FECHA_CIERRE fecha = new CON_FECHA_CIERRE();
        fecha.setCon(con); 

        int mes=fecha.mesActual();
        int ano=fecha.anoActual();
        
        for(RHH_PAGO_SUBSIDIOS pago:pagos)
        {
            html+="<tr>";
            if(pago.getESTADO()==0)
            html+="<td><span>PAGADO POR RECURSOS HUMANOS</span></td>";
            if(pago.getESTADO()==1)
            html+="<td><span>PENDIENTE</span></td>";
            if(pago.getESTADO()==2)
            html+="<td><span  style='color:#ff0000;'>ANULADO</span></td>";
            if(pago.getESTADO()==3)
            html+="<td><span style='color:#ff0000;'>RECHAZADO</span></td>";
            if(pago.getESTADO()==4)
            html+="<td><span>PAGADO POR CONTABILIDAD</span></td>";
            if(pago.getESTADO()==5)
            html+="<td><span>EN ESPERA DE PAGO POR CONTABILIDAD</span></td>";
            
            html+="<td>"+pago.getCUOTA()+"</td>";
            
            html+="<td>"+pago.getMONTO()+"</td>";
            html+="<td>"+pago.getFECHA_PAGO()+"</td>";
            if(pago.getESTADO()==0||pago.getESTADO()==4)
            html+="<td><span>"+pago.getFECHA_PAGADO()+"</span></td>";
            else
            html+="<td><span></span></td>";
            
            html+="<td>";
            if(pago.getESTADO()==1||pago.getESTADO()==3)
            {
                html+="<button type='button' onclick='pagar("+pago.getID()+",this);'>PAGAR</button><button type='button' onclick='anular("+pago.getID()+",this);'>ANULAR</button>";
                CON_RECURRENTES_MENSUALES crm = new CON_RECURRENTES_MENSUALES();
                crm.setCon(con);                
            }
            if(pago.getESTADO()==4)
            {
                CON_RECURRENTES_MENSUALES crm = new CON_RECURRENTES_MENSUALES();
                crm.setCon(con);                
                if(!crm.Existe(mes, ano, 8.0))                
                    html+="<button type='button' onclick='pagar("+pago.getID()+",this);'>VOLVER A PAGAR</button>";
                
            }
            html+="</td>";
            html+="<td><button onclick='eliminar("+pago.getID()+",this);'>ELIMINAR</button></td>";
            html+="</tr>";            
        }                
                
        return html;
    }

    private String crear3(HttpServletRequest request, Conexion con) throws SQLException, ParseException {
        String html="";
        int idsub = Integer.parseInt(request.getParameter("idsub"));
        int cantidad =new  RHH_PAGO_SUBSIDIOS(con).CantidadDePagos(idsub);
        Double monto = Double.parseDouble(request.getParameter("monto"));
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat format1 = new SimpleDateFormat("dd/MMMM/yyyy");
        Date fechapago = format.parse(request.getParameter("fecha3"));
        RHH_PAGO_SUBSIDIOS pago = new RHH_PAGO_SUBSIDIOS(0, idsub, 1, monto, cantidad+1, "", fechapago, null);
        pago.setCon(con);
        int id = pago.Insertar();
        html+="<tr><td><span>PENDIENTE</span></td><td>"+(cantidad+1)+"</td><td>"+monto+"</td><td>"+format1.format(fechapago)+"</td><td></td><td><button type='button' onclick='pagar("+id+",this);'>PAGAR</button><button type='button' onclick='anular("+id+");'>ANULAR</button></td><td><button onclick='eliminar("+pago.getID()+",this);'>ELIMINAR</button></td></tr>";
        return html;
    }

    private String pagar(HttpServletRequest request, Conexion con) throws SQLException {
        int idpago = Integer.parseInt(request.getParameter("idpago"));
        RHH_PAGO_SUBSIDIOS pagos = new RHH_PAGO_SUBSIDIOS(con).Buscar(idpago);
        pagos.setCon(con);
        pagos.setESTADO(0);
        Calendar cal = new GregorianCalendar();
        pagos.setFECHA_PAGADO(cal.getTime());
        pagos.Modificar();        
        SimpleDateFormat formato = new SimpleDateFormat("dd/MMMM/yyyy");
        return formato.format(cal.getTime());
    }

    private String anular(HttpServletRequest request, Conexion con) throws SQLException {
        int idpago = Integer.parseInt(request.getParameter("idpago"));
        RHH_PAGO_SUBSIDIOS pagos = new RHH_PAGO_SUBSIDIOS(con).Buscar(idpago);
        pagos.setCon(con);
        pagos.setESTADO(2);                
        pagos.Modificar();        
        return true+"";
    }

    private String inicio(HttpServletRequest request, Conexion con) throws SQLException {
        List<RHH_SUBSIDIOS> subsidios = new RHH_SUBSIDIOS(con).Todos();
        String html="";
        for(RHH_SUBSIDIOS subsidio:subsidios)
        {
            html+="<tr>";
            RHH_USUARIO us = new RHH_USUARIO(con).BuscarXid(subsidio.getID_USUARIO());
            RHH_PERSONA per = new RHH_PERSONA(con).BuscarxID(us.getID_PERSONA());                    
            int pagos = new RHH_PAGO_SUBSIDIOS(con).CantidadDePagos(subsidio.getID());
            html+="<td>"+per.getCI()+"</td>";
            html+="<td>"+per.getPRIMER_NOMBRE()+"</td>";
            html+="<td>"+per.getPRIMER_APELLIDO()+"</td>";
            if(subsidio.getBENEFICIARIO()==null)
            html+="<td></td>";
            else
            html+="<td>"+subsidio.getBENEFICIARIO()+"</td>";
            html+="<td><a href='#' onclick='cuotas("+subsidio.getID()+");'>"+pagos+"</a></td>";
            if(subsidio.getTIPO()==0)
                html+="<td>PRE-NATAL</td>";
            if(subsidio.getTIPO()==1)
                html+="<td>NATALIDAD</td>";
            if(subsidio.getTIPO()==2)
                html+="<td>POST-NATAL</td>";
            html+="<td>"+subsidio.getFECHA_INI()+"</td>";
            html+="</tr>";
        }
        return html;
    }

    private String eliminar(HttpServletRequest request, Conexion con) throws SQLException {
        int idpago = Integer.parseInt(request.getParameter("idpago"));
        RHH_PAGO_SUBSIDIOS pagos = new RHH_PAGO_SUBSIDIOS(con).Buscar(idpago);
        pagos.EliminarXid();
        return true+"";
    }
}
